package com.enjoylearning.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.learning.config.PayNotifyConfig;
import com.enjoylearning.learning.service.MyCourseTablesService;
import com.enjoylearning.messagesdk.model.po.MqMessage;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ReceivePayNotifyService {

    @Autowired
    MyCourseTablesService myCourseTablesService;

    //消费端处理消息，方法中的异常都会导致重试
    @RabbitListener(queues = PayNotifyConfig.PAYNOTIFY_QUEUE)
    public void receive(Message message, Channel channel) {
        //解析出消息
        byte[] body = message.getBody();
        String jsonString = new String(body);
        //转成对象
        MqMessage mqMessage = JSON.parseObject(jsonString, MqMessage.class);
        //根据消息选课id更新选课记录表和向选课表插入
        String id = mqMessage.getBusinessKey1();
        //订单类型
        String type = mqMessage.getBusinessKey2();
        //购买课程类型的消息
        if (type.equals("60201")){
            boolean b = myCourseTablesService.saveChooseCourseSuccess(id);
            if (!b){
                XueChengPlusException.cast("保存课程失败");
            }
        }
    }
}
